#include "Recognizer.h"



Recognizer::Recognizer (Ptr< queue< Request > > pRequestQueue,
                        float* pX, float* pY)
{
  _pRequestQueue = pRequestQueue;
  _pXSpace = pX;
  _pYSpace = pY;
	_init ();
  _load_grammar (GRAMMAR_FILE);
}


bool Recognizer::_init()
{
	HRESULT hr;

	hr=_cpRecoEngine.CoCreateInstance(CLSID_SpSharedRecognizer);
	if(FAILED(hr))
		return false;

	hr=_cpRecoEngine->CreateRecoContext(&_cpRecoContext);
	if(FAILED(hr))
		return false;

	hr=_cpRecoContext->SetNotifyWin32Event();
	if(FAILED(hr))
		return false;

	return true;
}

bool Recognizer::_load_grammar (wchar_t* file)
{
	HRESULT hr;

	hr = _cpRecoContext->CreateGrammar (1, &_cpGrammar);
	if (FAILED (hr))
		return false;

	hr = _cpGrammar->LoadCmdFromFile (file, SPLO_DYNAMIC);
	if (FAILED (hr))
		return false;

	hr = _cpGrammar->SetRuleState (NULL, NULL, SPRS_ACTIVE);
	if (FAILED (hr))
		return false;

  return true;

}

void Recognizer::startup()
{
	printf("Recognizer Here\n");
	while (true)
	{
		_cpRecoContext->WaitForNotifyEvent(INFINITE);
		_recognize();
	}
}

void Recognizer::_recognize ()
{
	CSpEvent event;

	while (event.GetFrom (_cpRecoContext) == S_OK)
	{
		ISpPhrase* pPhrase = event.RecoResult ();

		SPPHRASE* pElements;

		if(SUCCEEDED (pPhrase->GetPhrase (&pElements)))
		{
			switch (pElements->Rule.ulId)
			{
				case VID_Create:
				{
					switch (pElements->pProperties->vValue.ulVal)
					{
						case VID_Army:
							_gen_request (Request::Create, "army");
							break;
					}

				}
				break;
				case VID_Move:
				{
					_gen_request(Request::Move,"army");
					break;
				}
				break;
				case VID_Select:
				{
					_gen_request(Request::Select , "army");
					break;
				}
				break;
				case VID_Fight:
				{
					_gen_request(Request::Fight , "army");
					break;
				}
				break;
				case VID_Delete:
				{
					_gen_request(Request::Delete , "army");
					break;
				}
				break;
			}
		}
	}
}

void Recognizer::_gen_request (Request::RequestType type, char *object)
{
	Request request;
	request.requestType = type;
	request.type = ARMY;
	request.x = *_pXSpace;
	request.y = *_pYSpace;

	_pRequestQueue->push (request);
}